<?php

namespace app\index\service;

use app\common\model\AccessLog;
use app\common\model\Member;
use ShidianUtil\Utils\StringUtil;
use think\facade\Config;
use think\facade\Log;

/**
 * 微信公众号
 * Class WechatSubscription
 * @package app\index\service
 */
class WechatSubscription
{

    /**
     * 处理输入
     * @param $input
     * @return array|null
     */
    public function handle($input)
    {

        $result = null;
        $msgType = $input['MsgType'] ?? '';

        if ($msgType) {

            if (StringUtil::equals($msgType, 'event')) {
                //发生了事件

                $result = $this->event($input);
            } else {
                //其他情况

                $result = $this->msg($input);
            }
        }

        return $result;
    }

    private function event($input)
    {
        $result = null;
        $event = array_key_exists('Event', $input) ? $input['Event'] : '';
        switch ($event) {
            case 'subscribe':
                $result = $this->subscribe($input);
                break;
            case 'unsubscribe':
                $result = $this->unsubscribe($input);
                break;
        }

        return $result;
    }

    private function msg($input)
    {

        $content = '谢谢关注！';

        return [
            'ToUserName' => $input['FromUserName'],
            'FromUserName' => $input['ToUserName'],
            'CreateTime' => time(),
            'MsgType' => 'text',
            'Content' => $content
        ];
    }

    // 关注
    private function subscribe($input)
    {
        $openid = $input['FromUserName'] ?? '';

        if (StringUtil::notBlank($openid)) {
            $this->bind($openid);
        }

        // 发消息
        $this->sendSubscribeMessage($openid);

        return null;
    }

    // 取消关注
    private function unsubscribe($input)
    {
        $openid = $input['FromUserName'] ?? '';

        Log::info('$openid = ' . $openid);

        if (StringUtil::notBlank($openid)) {

            Member::where('openidWechat', $openid)->update([
                'followedWechat' => '0',
            ]);
        }


        return null;
    }

    // 绑定
    private function bind($open_id): void
    {
        $response = $this->getWechat()
            ->subscription(SUBSCRIPTION)
            ->user()
            ->info($open_id);

        if (!$response->isSuccess()) {
            return;
        }

        $decodeContents = $response->getDecodeContents();

        $union_id = $decodeContents['unionid'] ?? '';
        if (StringUtil::isBlank($union_id)) {
            return;
        }

        // "subscribe": 1,
        // "openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M",
        // "language": "zh_CN",
        // "subscribe_time": 1382694957,
        // "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL",
        // "remark": "",
        // "groupid": 0,
        // "tagid_list":[128,2],
        // "subscribe_scene": "ADD_SCENE_QR_CODE",
        // "qr_scene": 98765,
        // "qr_scene_str": ""

        $wechatInfo = [
            'unionid' => $decodeContents['unionid'] ?? null,
            'openidWechat' => $decodeContents['openid'] ?? null,
            'followedWechat' => '1',
        ];
        $this->getSessionWechatService()->initWechatInfo($wechatInfo);

    }

    // 关注公众号后发送消息
    private function sendSubscribeMessage($openid)
    {

        $miniprogramAppid = Config::get('wechat.' . MINIPROGRAM . '.AppID');

        // 客服消息
        $customMessage = $this->getWechat()
            ->subscription(SUBSCRIPTION)
            ->customMessage();

        // 第1条
        $msgtype = 'text';
        $data = [
            'content' => '🔥遇到法律纠纷不知道怎么办？'
        ];
        $customMessage->send($openid, $msgtype, $data);

        // 第2条
        $path0 = AccessLog::PAGE_MEMBER_SOUYE . '?from=gzh&poi=101';
        $path1 = AccessLog::PAGE_MEMBER_SOUYE . '?from=gzh&poi=102';
        $path2 = AccessLog::PAGE_MEMBER_SOUYE . '?from=gzh&poi=103';
        $path3 = AccessLog::PAGE_MEMBER_SOUYE . '?from=gzh&poi=104';
        $msgtype = 'text';
        $data = [
            'content' => '👉欢迎咨询熊猫律师，15万律师在线，1对1快速解决您的法律难题！
1、已支付，点击<a href="https://m.xiongmaolvshi.cn" data-miniprogram-appid="' . $miniprogramAppid . '" data-miniprogram-path="' . $path0 . '">【查看问题回复】</a>
2、律师回复后会通过手机短信提醒，请留意短信
3、更多服务
👉点击<a href="https://m.xiongmaolvshi.cn" data-miniprogram-appid="' . $miniprogramAppid . '" data-miniprogram-path="' . $path1 . '">【免费问律师】</a>获得专业律师1对1服务
👉点击<a href="https://m.xiongmaolvshi.cn" data-miniprogram-appid="' . $miniprogramAppid . '" data-miniprogram-path="' . $path2 . '">【极速咨询】</a>最快10秒回拨
👉点击<a href="https://m.xiongmaolvshi.cn" data-miniprogram-appid="' . $miniprogramAppid . '" data-miniprogram-path="' . $path3 . '">【电话咨询】</a>不限提问次数',
        ];
        $customMessage->send($openid, $msgtype, $data);

        // 第3条
        $msgtype = 'miniprogrampage';
        $data = [
            'title' => '金牌律师1对1，快速解决问题',
            'appid' => $miniprogramAppid,
            'pagepath' => AccessLog::PAGE_MEMBER_SOUYE,
            'thumb_media_id' => 'EJRdjnW229e26oPY_uTQ2An5oZRJ5S6ms5BjmmoweILh3khDZqlPiNSqzxfgUOr-',
        ];
        $customMessage->send($openid, $msgtype, $data);
    }

    private function getWechat(): \ShidianUtil\Api\Tencent\Wechat\Wechat
    {
        return app(\ShidianUtil\Api\Tencent\Wechat\Wechat::class);
    }

    private function getSessionWechatService(): SessionWechatService
    {
        return app(SessionWechatService::class);
    }
}